{{define "content"}}
<div x-data="userManager()" x-init="init()">
    <!-- 页面标题 -->
    <div class="mb-6">
        <div class="flex items-center justify-between">
            <div>
                <h1 class="text-2xl font-bold text-gray-900">用户管理</h1>
                <p class="text-gray-600">管理系统用户账户、角色分配和权限设置</p>
            </div>
            <div class="flex space-x-3">
                <a href="/system/users/create" class="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 flex items-center">
                    <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6"></path>
                    </svg>
                    添加用户
                </a>
                <button @click="exportUsers()" class="bg-green-600 text-white px-4 py-2 rounded-lg hover:bg-green-700 flex items-center">
                    <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
                    </svg>
                    导出
                </button>
                <button @click="refreshUsers()" :disabled="refreshing" class="bg-gray-600 text-white px-4 py-2 rounded-lg hover:bg-gray-700 flex items-center disabled:opacity-50 disabled:cursor-not-allowed">
                    <svg class="w-5 h-5 mr-2" :class="{'animate-spin': refreshing}" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path>
                    </svg>
                    <span x-text="refreshing ? '刷新中' : '刷新'"></span>
                </button>
            </div>
        </div>
    </div>

    <!-- 统计卡片 -->
    <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-6">
        <div class="bg-white rounded-lg shadow-sm p-6">
            <div class="flex items-center">
                <div class="flex-shrink-0">
                    <div class="w-8 h-8 bg-blue-500 rounded-md flex items-center justify-center">
                        <svg class="w-5 h-5 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4.354a4 4 0 110 5.292M15 21H3v-1a6 6 0 0112 0v1zm0 0h6v-1a6 6 0 00-9-5.197m13.5-9a2.5 2.5 0 11-5 0 2.5 2.5 0 015 0z"></path>
                        </svg>
                    </div>
                </div>
                <div class="ml-4">
                    <p class="text-sm font-medium text-gray-500">总用户数</p>
                    <p class="text-2xl font-semibold text-gray-900" x-text="stats.total_users || 0"></p>
                </div>
            </div>
        </div>
        
        <div class="bg-white rounded-lg shadow-sm p-6">
            <div class="flex items-center">
                <div class="flex-shrink-0">
                    <div class="w-8 h-8 bg-green-500 rounded-md flex items-center justify-center">
                        <svg class="w-5 h-5 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                        </svg>
                    </div>
                </div>
                <div class="ml-4">
                    <p class="text-sm font-medium text-gray-500">活跃用户</p>
                    <p class="text-2xl font-semibold text-gray-900" x-text="stats.active_users || 0"></p>
                </div>
            </div>
        </div>
        
        <div class="bg-white rounded-lg shadow-sm p-6">
            <div class="flex items-center">
                <div class="flex-shrink-0">
                    <div class="w-8 h-8 bg-yellow-500 rounded-md flex items-center justify-center">
                        <svg class="w-5 h-5 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                        </svg>
                    </div>
                </div>
                <div class="ml-4">
                    <p class="text-sm font-medium text-gray-500">停用用户</p>
                    <p class="text-2xl font-semibold text-gray-900" x-text="stats.inactive_users || 0"></p>
                </div>
            </div>
        </div>
        
        <div class="bg-white rounded-lg shadow-sm p-6">
            <div class="flex items-center">
                <div class="flex-shrink-0">
                    <div class="w-8 h-8 bg-purple-500 rounded-md flex items-center justify-center">
                        <svg class="w-5 h-5 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"></path>
                        </svg>
                    </div>
                </div>
                <div class="ml-4">
                    <p class="text-sm font-medium text-gray-500">今日新增</p>
                    <p class="text-2xl font-semibold text-gray-900" x-text="stats.today_users || 0"></p>
                </div>
            </div>
        </div>
    </div>

    <!-- 搜索和筛选 -->
    <div class="bg-white rounded-lg shadow-sm p-6 mb-6">
        <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
            <div class="flex flex-col sm:flex-row gap-4">
                <!-- 搜索框 -->
                <div class="relative">
                    <input type="text" 
                           x-model="searchQuery" 
                           @input="searchUsers()" 
                           placeholder="搜索用户名、姓名、邮箱..." 
                           class="pl-10 pr-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 w-full sm:w-80">
                    <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                        <svg class="w-5 h-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path>
                        </svg>
                    </div>
                </div>
                
                <!-- 状态筛选 -->
                <select x-model="statusFilter" @change="filterUsers()" class="border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500">
                    <option value="">全部状态</option>
                    <option value="active">活跃</option>
                    <option value="inactive">停用</option>
                </select>
                
                <!-- 角色筛选 -->
                <select x-model="roleFilter" @change="filterUsers()" class="border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500">
                    <option value="">全部角色</option>
                    <template x-for="role in roles" :key="role.id">
                        <option :value="role.id" x-text="role.display_name"></option>
                    </template>
                </select>
            </div>
            
          
        </div>
    </div>

    <!-- 用户列表 -->
    <div class="bg-white rounded-lg shadow-sm overflow-hidden">
        <!-- 批量操作栏 -->
        <div x-show="selectedUsers.length > 0" class="bg-blue-50 border-b border-blue-200 px-6 py-3">
            <div class="flex items-center justify-between">
                <div class="flex items-center">
                    <span class="text-sm text-blue-700">已选择 <span x-text="selectedUsers.length"></span> 个用户</span>
                </div>
                <div class="flex space-x-2">
                    <button @click="batchActivateUsers()" :disabled="selectedUsers.length === 0" class="bg-green-600 text-white px-3 py-1 rounded text-sm hover:bg-green-700 disabled:opacity-50 disabled:cursor-not-allowed">
                        批量激活
                    </button>
                    <button @click="batchDeactivateUsers()" :disabled="selectedUsers.length === 0" class="bg-yellow-600 text-white px-3 py-1 rounded text-sm hover:bg-yellow-700 disabled:opacity-50 disabled:cursor-not-allowed">
                        批量停用
                    </button>
                    <button @click="batchDeleteUsers()" :disabled="selectedUsers.length === 0" class="bg-red-600 text-white px-3 py-1 rounded text-sm hover:bg-red-700 disabled:opacity-50 disabled:cursor-not-allowed">
                        批量删除
                    </button>
                    <button @click="selectedUsers = []" class="bg-gray-600 text-white px-3 py-1 rounded text-sm hover:bg-gray-700">
                        取消选择
                    </button>
                </div>
            </div>
        </div>
        
        <!-- 表格头部 -->
        <div class="px-6 py-4 border-b border-gray-200">
            <div class="flex items-center justify-between">
                <h3 class="text-lg font-medium text-gray-900">用户列表</h3>
                <div class="text-sm text-gray-500">
                    共 <span x-text="pagination.total"></span> 个用户
                </div>
            </div>
        </div>
        
        <!-- 表格内容 -->
        <div class="overflow-x-auto">
            <!-- Loading状态 -->
            <div x-show="loading" class="flex justify-center items-center py-12">
                <div class="text-center">
                    <svg class="animate-spin w-10 h-10 text-blue-500 mb-4 mx-auto" fill="none" viewBox="0 0 24 24">
                        <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                        <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                    </svg>
                    <p class="text-gray-600">加载中...</p>
                </div>
            </div>
            
            <!-- 表格 -->
            <table x-show="!loading" class="min-w-full divide-y divide-gray-200">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            <input type="checkbox" @change="toggleSelectAll()" :checked="isAllSelected()" class="rounded border-gray-300 text-blue-600 focus:ring-blue-500">
                        </th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            用户信息
                        </th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            联系方式
                        </th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            角色
                        </th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            状态
                        </th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            最后登录
                        </th>
                        <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
                            操作
                        </th>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200">
                    <!-- 空状态 -->
                    <tr x-show="users.length === 0 && !loading">
                        <td colspan="7" class="px-6 py-12 text-center text-gray-500">
                            <div class="flex flex-col items-center">
                                <svg class="w-16 h-16 text-gray-300 mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4.354a4 4 0 110 5.292M15 21H3v-1a6 6 0 0112 0v1zm0 0h6v-1a6 6 0 00-9-5.197m13.5-9a2.5 2.5 0 11-5 0 2.5 2.5 0 015 0z"></path>
                                </svg>
                                <p class="text-lg font-medium mb-2">暂无用户数据</p>
                                <p class="text-sm mb-4" x-text="searchQuery || statusFilter || roleFilter ? '没有找到符合条件的用户，请尝试调整搜索条件' : '请检查筛选条件或添加新用户'"></p>
                                <div class="flex space-x-3 justify-center">
                                    <button x-show="searchQuery || statusFilter || roleFilter" @click="clearFilters()" class="bg-gray-600 text-white px-4 py-2 rounded-lg hover:bg-gray-700 text-sm">
                                        清除筛选
                                    </button>
                                    <a href="/system/users/create" class="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 text-sm">
                                        添加用户
                                    </a>
                                </div>
                            </div>
                        </td>
                    </tr>
                    

                    
                    <!-- 用户列表 -->
                    <template x-for="user in users" :key="user.id">
                        <tr class="hover:bg-gray-50">
                            <!-- 选择框 -->
                            <td class="px-6 py-4 whitespace-nowrap">
                                <div class="flex items-center">
                                    <input type="checkbox" 
                                           :value="user.id" 
                                           x-model="selectedUsers" 
                                           :disabled="isSystemAdmin(user)"
                                           :class="isSystemAdmin(user) ? 'opacity-50 cursor-not-allowed' : ''"
                                           class="rounded border-gray-300 text-blue-600 focus:ring-blue-500">
                                    <span x-show="isSystemAdmin(user)" 
                                          class="ml-2 text-xs bg-red-100 text-red-800 px-2 py-1 rounded-full"
                                          title="系统管理员">
                                        管理员
                                    </span>
                                </div>
                            </td>
                            
                            <!-- 用户信息 -->
                            <td class="px-6 py-4 whitespace-nowrap">
                                <div class="flex items-center">
                                    <div class="flex-shrink-0 h-10 w-10">
                                        <div class="h-10 w-10 rounded-full bg-blue-500 flex items-center justify-center text-white font-medium" 
                                             x-text="user.real_name ? user.real_name.charAt(0).toUpperCase() : user.username.charAt(0).toUpperCase()"></div>
                                    </div>
                                    <div class="ml-4">
                                        <div class="text-sm font-medium text-gray-900">
                                            <a :href="'/system/users/detail/' + user.id" class="hover:text-blue-600" x-text="user.username"></a>
                                        </div>
                                        <div class="text-sm text-gray-500" x-text="user.real_name"></div>
                                    </div>
                                </div>
                            </td>
                            
                            <!-- 联系方式 -->
                            <td class="px-6 py-4 whitespace-nowrap">
                                <div class="text-sm text-gray-900" x-text="user.phone || '-'"></div>
                                <div class="text-sm text-gray-500" x-text="user.email || '-'"></div>
                            </td>
                            
                            <!-- 角色 -->
                            <td class="px-6 py-4 whitespace-nowrap">
                                <div class="flex flex-wrap gap-1">
                                    <template x-for="role in (user.roles || [])" :key="role.id">
                                        <span class="inline-flex px-2 py-1 text-xs font-semibold rounded-full bg-purple-100 text-purple-800" 
                                              x-text="role.display_name"></span>
                                    </template>
                                    <span x-show="!user.roles || user.roles.length === 0" 
                                          class="inline-flex px-2 py-1 text-xs font-semibold rounded-full bg-gray-100 text-gray-800">无角色</span>
                                </div>
                            </td>
                            
                            <!-- 状态 -->
                            <td class="px-6 py-4 whitespace-nowrap">
                                <button @click="toggleUserStatus(user)" 
                                        :disabled="isSystemAdmin(user) && user.status === 'active'"
                                        :class="isSystemAdmin(user) && user.status === 'active' ? 
                                                'bg-green-100 text-green-800 cursor-not-allowed opacity-75' : 
                                                (user.status === 'active' ? 'bg-green-100 text-green-800 hover:bg-green-200 cursor-pointer' : 'bg-red-100 text-red-800 hover:bg-red-200 cursor-pointer')"
                                        :title="isSystemAdmin(user) && user.status === 'active' ? '系统管理员不能停用' : '点击切换状态'"
                                        class="inline-flex px-2 py-1 text-xs font-semibold rounded-full" 
                                        x-text="user.status === 'active' ? '活跃' : '停用'"></button>
                            </td>
                            
                            <!-- 最后登录 -->
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                <span x-text="formatDateTime(user.last_login_at)"></span>
                            </td>
                            
                            <!-- 操作 -->
                            <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                                <div class="flex items-center justify-end space-x-2">
                                    <a :href="'/system/users/detail/' + user.id" class="text-blue-600 hover:text-blue-900" title="查看详情">
                                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path>
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"></path>
                                        </svg>
                                    </a>
                                    <a :href="'/system/users/edit/' + user.id" class="text-indigo-600 hover:text-indigo-900" title="编辑用户">
                                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"></path>
                                        </svg>
                                    </a>
                                    <button @click="manageUserRoles(user)" 
                                            :disabled="isSystemAdmin(user)"
                                            :class="isSystemAdmin(user) ? 'text-gray-400 cursor-not-allowed' : 'text-purple-600 hover:text-purple-900'"
                                            :title="isSystemAdmin(user) ? '系统管理员角色不可修改' : '管理角色'">
                                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"></path>
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path>
                                        </svg>
                                    </button>
                                    <button @click="resetPassword(user)" 
                                            :disabled="isSystemAdmin(user)"
                                            :class="isSystemAdmin(user) ? 'text-gray-400 cursor-not-allowed' : 'text-orange-600 hover:text-orange-900'"
                                            :title="isSystemAdmin(user) ? '系统管理员密码不可重置' : '重置密码'">
                                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 7a2 2 0 012 2m4 0a6 6 0 01-7.743 5.743L11 17H9v2H7v2H4a1 1 0 01-1-1v-2.586a1 1 0 01.293-.707l5.964-5.964A6 6 0 1121 9z"></path>
                                        </svg>
                                    </button>
                                    <button @click="deleteUser(user)" 
                                            :disabled="isSystemAdmin(user)"
                                            :class="isSystemAdmin(user) ? 'text-gray-400 cursor-not-allowed' : 'text-red-600 hover:text-red-900'"
                                            :title="isSystemAdmin(user) ? '系统管理员不能删除' : '删除用户'">
                                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path>
                                        </svg>
                                    </button>
                                </div>
                            </td>
                        </tr>
                    </template>
                </tbody>
            </table>
        </div>
        
        <!-- 分页 -->
        <div class="bg-white px-4 py-3 border-t border-gray-200 sm:px-6">
            <div class="flex items-center justify-between">
                <div class="flex-1 flex justify-between sm:hidden">
                    <button @click="previousPage()" 
                            :disabled="pagination.page <= 1"
                            class="relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 disabled:opacity-50">
                        上一页
                    </button>
                    <button @click="nextPage()" 
                            :disabled="pagination.page >= Math.ceil(pagination.total / pagination.limit)"
                            class="ml-3 relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 disabled:opacity-50">
                        下一页
                    </button>
                </div>
                <div class="hidden sm:flex-1 sm:flex sm:items-center sm:justify-between">
                    <div>
                        <p class="text-sm text-gray-700">
                            显示第 <span class="font-medium" x-text="(pagination.page - 1) * pagination.limit + 1"></span> 到 
                            <span class="font-medium" x-text="Math.min(pagination.page * pagination.limit, pagination.total)"></span> 条，
                            共 <span class="font-medium" x-text="pagination.total"></span> 条记录
                        </p>
                    </div>
                    <div>
                        <nav class="relative z-0 inline-flex rounded-md shadow-sm -space-x-px">
                            <button @click="previousPage()" 
                                    :disabled="pagination.page <= 1"
格的                                    class="relative inline-flex items-center px-2 py-2 rounded-l-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50 disabled:opacity-50">
                                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                     <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"></path>
                                 </svg>
                            </button>
                            <template x-for="page in getPageNumbers()" :key="page">
                                <button @click="goToPage(page)" 
                                        :class="page === pagination.page ? 'bg-blue-50 border-blue-500 text-blue-600' : 'bg-white border-gray-300 text-gray-500 hover:bg-gray-50'"
                                        class="relative inline-flex items-center px-4 py-2 border text-sm font-medium" 
                                        x-text="page"></button>
                            </template>
                            <button @click="nextPage()" 
                                    :disabled="pagination.page >= Math.ceil(pagination.total / pagination.limit)"
                                    class="relative inline-flex items-center px-2 py-2 rounded-r-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50 disabled:opacity-50">
                                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                     <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"></path>
                                 </svg>
                            </button>
                        </nav>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 角色管理模态框 -->
    <div x-show="showRoleModal" 
         x-transition:enter="transition ease-out duration-300"
         x-transition:enter-start="opacity-0"
         x-transition:enter-end="opacity-100"
         x-transition:leave="transition ease-in duration-200"
         x-transition:leave-start="opacity-100"
         x-transition:leave-end="opacity-0"
         class="fixed inset-0 z-50 overflow-y-auto">
        <div class="flex items-center justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
            <div class="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity"></div>
            
            <div class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">
                <form @submit.prevent="updateUserRoles()">
                    <div class="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
                        <div class="sm:flex sm:items-start">
                            <div class="w-full">
                                <h3 class="text-lg leading-6 font-medium text-gray-900 mb-4">
                                    管理用户角色 - <span x-text="roleForm.username"></span>
                                </h3>
                                
                                <div class="space-y-2 max-h-64 overflow-y-auto">
                                    <template x-for="role in roles" :key="role.id">
                                        <label class="flex items-center p-2 hover:bg-gray-50 rounded">
                                            <input type="checkbox" 
                                                   :value="role.id" 
                                                   x-model="roleForm.role_ids" 
                                                   class="rounded border-gray-300 text-blue-600 focus:ring-blue-500">
                                            <div class="ml-3">
                                                <div class="text-sm font-medium text-gray-900" x-text="role.display_name"></div>
                                                <div class="text-sm text-gray-500" x-text="role.description"></div>
                                            </div>
                                        </label>
                                    </template>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
                        <button type="submit" 
                                class="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-blue-600 text-base font-medium text-white hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 sm:ml-3 sm:w-auto sm:text-sm">
                            保存
                        </button>
                        <button type="button" 
                                @click="showRoleModal = false" 
                                class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm">
                            取消
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- 重置密码模态框 -->
    <div x-show="showResetPasswordModal" 
         x-transition:enter="transition ease-out duration-300"
         x-transition:enter-start="opacity-0"
         x-transition:enter-end="opacity-100"
         x-transition:leave="transition ease-in duration-200"
         x-transition:leave-start="opacity-100"
         x-transition:leave-end="opacity-0"
         class="fixed inset-0 z-50 overflow-y-auto">
        <div class="flex items-center justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
            <div class="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity"></div>
            
            <div class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-md sm:w-full">
                <form @submit.prevent="confirmResetPassword()">
                    <div class="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
                        <div class="sm:flex sm:items-start">
                            <div class="w-full">
                                <h3 class="text-lg leading-6 font-medium text-gray-900 mb-4">
                                    重置密码 - <span x-text="resetPasswordForm.username"></span>
                                </h3>
                                
                                <div class="space-y-4">
                                    <div>
                                        <label class="block text-sm font-medium text-gray-700">新密码 *</label>
                                        <input type="password" 
                                               x-model="resetPasswordForm.new_password" 
                                               required 
                                               minlength="6"
                                               class="mt-1 block w-full border border-gray-300 rounded-md px-3 py-2 focus:ring-blue-500 focus:border-blue-500">
                                    </div>
                                    
                                    <div>
                                        <label class="block text-sm font-medium text-gray-700">确认密码 *</label>
                                        <input type="password" 
                                               x-model="resetPasswordForm.confirm_password" 
                                               required 
                                               minlength="6"
                                               class="mt-1 block w-full border border-gray-300 rounded-md px-3 py-2 focus:ring-blue-500 focus:border-blue-500">
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
                        <button type="submit" 
                                class="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-red-600 text-base font-medium text-white hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500 sm:ml-3 sm:w-auto sm:text-sm">
                            重置密码
                        </button>
                        <button type="button" 
                                @click="showResetPasswordModal = false" 
                                class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm">
                            取消
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
function userManager() {
    return {
        // 数据
        users: [],
        roles: [],
        stats: {},
        selectedUsers: [],
        
        // 搜索和筛选
        searchQuery: '',
        statusFilter: '',
        roleFilter: '',
        
        // 分页
        pagination: {
            page: 1,
            limit: 10,
            total: 0
        },
        
        // 模态框状态
        showRoleModal: false,
        showResetPasswordModal: false,
        
        // 表单数据
        roleForm: {
            user_id: null,
            username: '',
            role_ids: []
        },
        resetPasswordForm: {
            user_id: null,
            username: '',
            new_password: '',
            confirm_password: ''
        },
        
        // 初始化状态
        initialized: false,
        loading: true,
        refreshing: false,
        
        // 初始化
        async init() {
            // 防止重复初始化
            if (this.initialized) {
                return;
            }
            
            try {
                await Promise.all([
                    this.loadStats(),
                    this.loadRoles(),
                    this.loadUsers()
                ]);
                this.initialized = true;
            } catch (error) {
                console.error('初始化失败:', error);
                this.showToast('页面初始化失败', 'error');
            } finally {
                this.loading = false;
            }
        },
        
        // 加载统计信息
        async loadStats() {
            try {
                const response = await fetch('/api/v1/users/stats');
                const result = await response.json();
                if (result.code === 200) {
                    this.stats = result.data;
                }
            } catch (error) {
                console.error('加载统计信息失败:', error);
            }
        },
        
        // 加载角色列表
        async loadRoles() {
            try {
                const response = await fetch('/api/v1/system/roles');
                const result = await response.json();
                if (result.code === 200) {
                    this.roles = result.data.list || [];
                }
            } catch (error) {
                console.error('加载角色列表失败:', error);
            }
        },
        
        // 加载用户列表
        async loadUsers() {
            this.loading = true;
            try {
                const params = new URLSearchParams({
                    page: this.pagination.page,
                    limit: this.pagination.limit,
                    search: this.searchQuery,
                    status: this.statusFilter,
                    role_id: this.roleFilter
                });
                
                console.log('正在加载用户列表，参数:', params.toString());
                const response = await fetch(`/api/v1/users?${params}`);
                const result = await response.json();
                
                console.log('用户列表API响应:', result);
                
                if (result.code === 200) {
                    this.users = result.data.users || [];
                    this.pagination.total = result.data.total || 0;
                    console.log('用户数据已加载:', this.users.length, '条记录');
                } else {
                    console.error('API返回错误:', result.message);
                    this.showToast(result.message || '加载用户列表失败', 'error');
                }
            } catch (error) {
                console.error('加载用户列表失败:', error);
                this.showToast('加载用户列表失败', 'error');
            } finally {
                this.loading = false;
            }
        },
        
        // 防抖搜索定时器
        searchTimer: null,
        
        // 搜索用户
        searchUsers() {
            // 清除之前的定时器
            if (this.searchTimer) {
                clearTimeout(this.searchTimer);
            }
            
            // 设置防抖延迟
            this.searchTimer = setTimeout(() => {
                this.pagination.page = 1;
                this.loadUsers();
            }, 300);
        },
        
        // 筛选用户
        filterUsers() {
            this.pagination.page = 1;
            this.loadUsers();
        },
        
        // 清除筛选条件
        clearFilters() {
            this.searchQuery = '';
            this.statusFilter = '';
            this.roleFilter = '';
            this.pagination.page = 1;
            this.loadUsers();
        },
        
        // 刷新用户列表
        async refreshUsers() {
            if (this.refreshing) {
                return;
            }
            
            this.refreshing = true;
            
            try {
                await Promise.all([
                    this.loadStats(),
                    this.loadUsers()
                ]);
            } catch (error) {
                console.error('刷新失败:', error);
            } finally {
                this.refreshing = false;
            }
        },
        
        // 切换用户状态
        async toggleUserStatus(user) {
            // 检查是否为系统管理员且要停用
            if (this.isSystemAdmin(user) && user.status === 'active') {
                this.showToast('系统管理员不能被停用', 'warning');
                return;
            }
            
            if (confirm(`确定要${user.status === 'active' ? '停用' : '激活'}用户 ${user.username} 吗？`)) {
                try {
                    const response = await fetch(`/api/v1/users/${user.id}/toggle-status`, {
                        method: 'POST'
                    });
                    const result = await response.json();
                    
                    if (result.code === 200) {
                        this.showToast(result.message, 'success');
                        // 避免重复调用，只刷新必要的数据
                        await this.refreshUsers();
                    } else {
                        this.showToast(result.message, 'error');
                    }
                } catch (error) {
                    this.showToast('操作失败', 'error');
                }
            }
        },
        
        // 管理用户角色
        async manageUserRoles(user) {
            // 检查是否为系统管理员
            if (this.isSystemAdmin(user)) {
                this.showToast('系统管理员的角色不可修改', 'warning');
                return;
            }
            
            this.roleForm = {
                user_id: user.id,
                username: user.username,
                role_ids: (user.roles || []).map(role => role.id)
            };
            this.showRoleModal = true;
        },
        
        // 更新用户角色
        async updateUserRoles() {
            try {
                const response = await fetch(`/api/v1/users/${this.roleForm.user_id}/roles`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        role_ids: this.roleForm.role_ids
                    })
                });
                
                const result = await response.json();
                
                if (result.code === 200) {
                    this.showToast('角色更新成功', 'success');
                    this.showRoleModal = false;
                    await this.loadUsers();
                } else {
                    this.showToast(result.message, 'error');
                }
            } catch (error) {
                this.showToast('角色更新失败', 'error');
            }
        },
        
        // 重置密码
        resetPassword(user) {
            // 检查是否为系统管理员
            if (this.isSystemAdmin(user)) {
                this.showToast('系统管理员的密码不可重置', 'warning');
                return;
            }
            
            this.resetPasswordForm = {
                user_id: user.id,
                username: user.username,
                new_password: '',
                confirm_password: ''
            };
            this.showResetPasswordModal = true;
        },
        
        // 确认重置密码
        async confirmResetPassword() {
            if (this.resetPasswordForm.new_password !== this.resetPasswordForm.confirm_password) {
                this.showToast('两次输入的密码不一致', 'error');
                return;
            }
            
            try {
                const response = await fetch(`/api/v1/users/${this.resetPasswordForm.user_id}/reset-password`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        new_password: this.resetPasswordForm.new_password
                    })
                });
                
                const result = await response.json();
                
                if (result.code === 200) {
                    this.showToast('密码重置成功', 'success');
                    this.showResetPasswordModal = false;
                } else {
                    this.showToast(result.message, 'error');
                }
            } catch (error) {
                this.showToast('密码重置失败', 'error');
            }
        },
        
        // 检查是否为系统管理员
        isSystemAdmin(user) {
            if (!user.roles || user.roles.length === 0) return false;
            return user.roles.some(role => role.name === 'admin' || role.name === 'system_admin' || role.display_name === '系统管理员');
        },
        
        // 删除用户
        async deleteUser(user) {
            // 检查是否为系统管理员
            if (this.isSystemAdmin(user)) {
                this.showToast('系统管理员不能被删除', 'warning');
                return;
            }
            
            if (confirm(`确定要删除用户 ${user.username} 吗？此操作不可恢复！`)) {
                try {
                    const response = await fetch(`/api/v1/users/${user.id}`, {
                        method: 'DELETE'
                    });
                    const result = await response.json();
                    
                    if (result.code === 200) {
                        this.showToast('用户删除成功', 'success');
                        // 避免重复调用，只刷新必要的数据
                        await this.refreshUsers();
                    } else {
                        this.showToast(result.message, 'error');
                    }
                } catch (error) {
                    this.showToast('删除失败', 'error');
                }
            }
        },
        
        // 批量删除用户
        async batchDeleteUsers() {
            if (this.selectedUsers.length === 0) {
                this.showToast('请选择要删除的用户', 'warning');
                return;
            }
            
            // 检查选中的用户中是否包含系统管理员
            const selectedUserObjects = this.users.filter(user => this.selectedUsers.includes(user.id));
            const adminUsers = selectedUserObjects.filter(user => this.isSystemAdmin(user));
            
            if (adminUsers.length > 0) {
                const adminNames = adminUsers.map(user => user.username).join('、');
                this.showToast(`选中的用户中包含系统管理员（${adminNames}），无法删除`, 'warning');
                return;
            }
            
            if (confirm(`确定要删除选中的 ${this.selectedUsers.length} 个用户吗？此操作不可恢复！`)) {
                try {
                    const response = await fetch('/api/v1/users/batch-delete', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            user_ids: this.selectedUsers
                        })
                    });
                    
                    const result = await response.json();
                    
                    if (result.code === 200) {
                        this.showToast('批量删除成功', 'success');
                        this.selectedUsers = [];
                        // 避免重复调用，只刷新必要的数据
                        await this.refreshUsers();
                    } else {
                        this.showToast(result.message, 'error');
                    }
                } catch (error) {
                    this.showToast('批量删除失败', 'error');
                }
            }
        },
        
        // 全选/取消全选
        toggleSelectAll() {
            if (this.isAllSelected()) {
                this.selectedUsers = [];
            } else {
                this.selectedUsers = this.users.map(user => user.id);
            }
        },
        
        // 检查是否全选
        isAllSelected() {
            return this.users.length > 0 && this.selectedUsers.length === this.users.length;
        },
        
        // 分页相关
        previousPage() {
            if (this.pagination.page > 1) {
                this.pagination.page--;
                this.loadUsers();
            }
        },
        
        nextPage() {
            const maxPage = Math.ceil(this.pagination.total / this.pagination.limit);
            if (this.pagination.page < maxPage) {
                this.pagination.page++;
                this.loadUsers();
            }
        },
        
        goToPage(page) {
            this.pagination.page = page;
            this.loadUsers();
        },
        
        getPageNumbers() {
            const maxPage = Math.ceil(this.pagination.total / this.pagination.limit);
            const pages = [];
            const start = Math.max(1, this.pagination.page - 2);
            const end = Math.min(maxPage, this.pagination.page + 2);
            
            for (let i = start; i <= end; i++) {
                pages.push(i);
            }
            
            return pages;
        },
        
        // 导出用户数据
        async exportUsers() {
            try {
                const params = new URLSearchParams({
                    search: this.searchQuery,
                    status: this.statusFilter,
                    role_id: this.roleFilter,
                    export: 'true'
                });
                
                const response = await fetch(`/api/v1/users/export?${params}`);
                
                if (response.ok) {
                    const blob = await response.blob();
                    const url = window.URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.href = url;
                    a.download = `用户列表_${new Date().toISOString().split('T')[0]}.xlsx`;
                    document.body.appendChild(a);
                    a.click();
                    document.body.removeChild(a);
                    window.URL.revokeObjectURL(url);
                    this.showToast('导出成功', 'success');
                } else {
                    this.showToast('导出失败', 'error');
                }
            } catch (error) {
                console.error('导出失败:', error);
                this.showToast('导出失败', 'error');
            }
        },
        
        // 批量激活用户
        async batchActivateUsers() {
            if (this.selectedUsers.length === 0) {
                this.showToast('请选择要激活的用户', 'warning');
                return;
            }
            
            if (confirm(`确定要激活选中的 ${this.selectedUsers.length} 个用户吗？`)) {
                try {
                    const response = await fetch('/api/v1/users/batch-activate', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            user_ids: this.selectedUsers
                        })
                    });
                    
                    const result = await response.json();
                    
                    if (result.code === 200) {
                        this.showToast('批量激活成功', 'success');
                        this.selectedUsers = [];
                        await this.refreshUsers();
                    } else {
                        this.showToast(result.message, 'error');
                    }
                } catch (error) {
                    this.showToast('批量激活失败', 'error');
                }
            }
        },
        
        // 批量停用用户
        async batchDeactivateUsers() {
            if (this.selectedUsers.length === 0) {
                this.showToast('请选择要停用的用户', 'warning');
                return;
            }
            
            // 检查选中的用户中是否包含系统管理员
            const selectedUserObjects = this.users.filter(user => this.selectedUsers.includes(user.id));
            const adminUsers = selectedUserObjects.filter(user => this.isSystemAdmin(user));
            
            if (adminUsers.length > 0) {
                const adminNames = adminUsers.map(user => user.username).join('、');
                this.showToast(`选中的用户中包含系统管理员（${adminNames}），无法停用`, 'warning');
                return;
            }
            
            if (confirm(`确定要停用选中的 ${this.selectedUsers.length} 个用户吗？`)) {
                try {
                    const response = await fetch('/api/v1/users/batch-deactivate', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            user_ids: this.selectedUsers
                        })
                    });
                    
                    const result = await response.json();
                    
                    if (result.code === 200) {
                        this.showToast('批量停用成功', 'success');
                        this.selectedUsers = [];
                        await this.refreshUsers();
                    } else {
                        this.showToast(result.message, 'error');
                    }
                } catch (error) {
                    this.showToast('批量停用失败', 'error');
                }
            }
        },
        
        // 工具函数
        formatDateTime(dateTime) {
            if (!dateTime) return '-';
            return new Date(dateTime).toLocaleString('zh-CN');
        },
        
        showToast(message, type = 'info') {
            // 这里可以集成一个 toast 组件
            console.log(`${type}: ${message}`); 
        }
    };
}
</script>
{{end}}